package Huihu.src.Duoxiancheng;
//抢票不安全
public class UnsafeBuyTicket {

    public static class BuyTicket implements Runnable{
        private int ticket=10;
        boolean falg=true;

        @Override
        public void run() {
            //买票
            while (falg) {
                try {
                    buy();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        public synchronized void buy() throws InterruptedException {
            //判断是否有票
            if (ticket<=0) {
                falg=false;
                return;
            }
            //模拟延时
            Thread.sleep(100);
            //买票
            System.out.println(Thread.currentThread().getName()+"在抢第"+ticket--+"张票");
        }
    }

    public static void main(String[] args) {
        BuyTicket buyTicket=new BuyTicket();
        new Thread(buyTicket,"张三").start();
        new Thread(buyTicket,"李四").start();
        new Thread(buyTicket,"王五").start();
    }
}
